﻿package com.jianghu.helpers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.util.Log;

import com.jianghu.R;
import com.jianghu.RecommendActivity;
import com.jianghu.dto.RecommendArticle;

public  class CacheManager{
	private static long FILE_NAME = 0x1000000;
	private static final String LOCAL = "http://10.0.2.2:8080/jianghu";
	private static int MAX_CACHE_SIZE = 1024;
	private static HashMap<URL, Object> cacheMap = new HashMap<URL, Object>();
	private Context context;
	
	public CacheManager(Context context) {
		super();
		this.context = context;
	}

	public boolean isCached(URL url){
		return cacheMap.containsKey(url);
	}
	
	/**
	 * 通过URL拿到本地的一个InputStream
	 * @param url
	 * @return A null value returned If not found the InputStream in local
	 */
	public InputStream getCacheData(URL url) throws FileNotFoundException{
		Object resource = cacheMap.get(url);
		if(resource instanceof Integer){
			return context.getResources().openRawResource((Integer) resource);
		}else if(resource instanceof String){
			return context.openFileInput((String) resource);
		}
		
		throw new FileNotFoundException();
	}
	
	public synchronized boolean addCacheData(URL url, InputStream is){
		String fileName = "cache_"+FILE_NAME;
		FILE_NAME ++;
		Object oldFile = cacheMap.get(url);
		try {
			if(oldFile instanceof String){
				File file = new File(context.getFilesDir(), (String) oldFile);
				file.delete();
			}
		} catch (Exception e1) {
			Log.d("jianghu", "File can not delete. "+oldFile);
		}
		
		try {
			OutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			while(is.available() > 0){
				byte[] buf = new byte[1024];
				is.read(buf);
				out.write(buf);
			}
			
			out.flush();
			out.close();
			cacheMap.put(url, fileName);
			return true;
		} catch (FileNotFoundException e) {
			Log.d("jianghu", "File can not found. "+fileName);
		} catch (IOException e) {
			Log.d("jianghu", "IO Exception ", e);
		}
		
		return false;
	}
	
	static{
		initData();
	}
	
	private static void initData(){
		try {
			cacheMap.put(new URL(LOCAL + RecommendActivity.CONTENT_PATH) , R.raw.rec_list);
			cacheMap.put(new URL("http://xx.xx.xx/jianghu/icon/comments_icon.png") , R.raw.comments_icon);
			
		} catch (MalformedURLException e) {
			Log.d("jianghu", "cacheManager init exception", e);
		}
	}
	
	public void refresh() {
		cacheMap.clear();
		initData();
	}
}